from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import DescribeRegionsRequest, DescribeInstancesRequest, DescribeZonesRequest, \
    DescribeDisksRequest
import json


class AliCloud():
    def __init__(self, secret_id, secret_key):
        self.secret_id = secret_id
        self.secret_key = secret_key

    def region_list(self):
        client = AcsClient(self.secret_id, self.secret_key)
        req = DescribeRegionsRequest.DescribeRegionsRequest()  # 获取地区
        try:
            resp = client.do_action_with_exception(req)
            resp = json.loads(resp.decode())
            resp = {'code': 200, 'data': resp}
            return resp
        except Exception as e:
            return {'code': '500', 'msg': e.get_error_msg()}

    def zone_list(self, region_id):
        client = AcsClient(self.secret_id, self.secret_key)
        req = DescribeZonesRequest.DescribeZonesRequest()
        req.add_query_param('RegionId', region_id)
        try:
            resp = client.do_action_with_exception(req)
            resp = json.loads(resp.decode())
            resp = {'code': 200, 'data': resp}
            return resp
        except Exception as e:
            return {'code': '500', 'msg': e.get_error_msg()}

    def instance_list(self, region_id):
        client = AcsClient(self.secret_id, self.secret_key)
        req = DescribeInstancesRequest.DescribeInstancesRequest()
        req.add_query_param('RegionId', region_id)
        try:
            resp = client.do_action_with_exception(req)
            resp = json.loads(resp.decode())
            resp = {'code': 200, 'data': resp}
            return resp
        except Exception as e:
            return {'code': '500', 'msg': e.get_error_msg()}

    def instance_disk(self, instance_id):
        client = AcsClient(self.secret_id, self.secret_key)
        req = DescribeDisksRequest.DescribeDisksRequest()
        req.add_query_param('InstanceId', instance_id)
        try:
            resp = client.do_action_with_exception(req)
            resp = json.loads(resp.decode())
            resp = {'code': 200, 'data': resp}
            return resp
        except Exception as e:
            return {'code': '500', 'msg': e.get_error_msg()}


if __name__ == '__main__':
    # 找个测试ak可以试试
    cloud = AliCloud("LTAI5tEDbr3UPGWrUeQbPfKo", "OGn0ESXEHKR29iNES8bCjibw1jo9sa")
    result = cloud.region_list()
    result = cloud.zone_list('cn-hangzhou')
    result = cloud.instance_list("cn-hangzhou")
    result = cloud.instance_disk("i-bp1g28isv8irjtrwdxf4")
    print(result)
